package com.xinhe.web.service;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.xinhe.web.common.BusinessException;
import com.xinhe.web.common.Result;
import com.xinhe.web.entity.QMember;
import com.xinhe.web.entity.QShop;
import com.xinhe.web.entity.Shop;
import com.xinhe.web.reposity.ShopRepository;
import com.xinhe.web.response.ShopView;
import com.xinhe.web.util.Snowflake;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.inject.Provider;
import javax.persistence.EntityManager;
import java.util.Date;

@Service
public class ShopService {
    @Autowired
    private ShopRepository shopRepository;

    //查询工厂
    private JPAQueryFactory queryFactory;
    @Autowired
    private Provider<EntityManager> entityManager;

    @PostConstruct
    public void init() {
        queryFactory = new JPAQueryFactory(entityManager);
    }

    public QueryResults<ShopView> pageShop(String name, int pageNum, int pageSize) {
        QShop qShop = QShop.shop;
        QMember qMember = QMember.member;
        BooleanBuilder builder = new BooleanBuilder();
        OrderSpecifier<Date> sort = qMember.createTime.desc();
        //builder.and(qShop.removed.eq(0));
        if (StringUtils.isNotEmpty(name)) {
            builder.and(qShop.name.contains(name));
        }
        return queryFactory.select(
                Projections.bean(
                        ShopView.class,
                        qShop.name,
                        qShop.userId,
                        qShop.address,
                        qShop.id,
                        qShop.iconPath,
                        qShop.area,
                        qShop.city,
                        qShop.detail,
                        qShop.province,
                        qShop.latitude,
                        qShop.longitude,
                        qShop.telephone,
                        qMember.nickname,
                        qShop.iconPath.as("userIconPath")
                )
        ).from(qShop)
                .leftJoin(qMember).on(qShop.userId.eq(qMember.fUserId))
                .where(builder).offset(pageNum * pageSize).limit(pageSize).orderBy(sort).fetchResults();
    }

    public Result<Shop> findById(Long shopId) {
        return Result.ok(shopRepository.findById(shopId).get());
    }

    public Result delete(Long shopId) {
        shopRepository.deleteById(shopId);
        return Result.ok();
    }
    @Transactional
    public Result saveShop(Long id,String name,String province,String city,String area,
                           String detail,String longitude, String latitude,String remark,
                           Long userId,String address) {
        Shop shop = null;
        Shop shopByName = shopRepository.findByName(name);
        if (shopByName != null && !shopByName.getId().equals(shop.getId())) {
            throw new BusinessException(4002,"自提点门店已存在");
        }

        if (id != null) {
            shop = shopRepository.findById(id).get();
            shop.setName(name);
            shop.setProvince(province);
            shop.setCity(city);
            shop.setArea(area);
            shop.setDetail(detail);
            shop.setLongitude(longitude);
            shop.setLatitude(latitude);
            shop.setUserId(userId);
            shop.setAddress(address);
            shopRepository.saveAndFlush(shop);
        } else {
            shop = new Shop();
            shop.setId(Snowflake.generateId());
            shop.setName(name);
            shop.setProvince(province);
            shop.setCity(city);
            shop.setArea(area);
            shop.setDetail(detail);
            shop.setLongitude(longitude);
            shop.setLatitude(latitude);
            shop.setUserId(userId);
            shop.setAddress(address);
            shopRepository.save(shop);
        }
        return Result.ok();
    }

}

    /*public PageResult<ShopDistanceView> pageShopDistance(ShopDistanceQuery query) {
        Integer total = Integer.valueOf(0);
        if (0 < query.getLimit().intValue()) {
            total = this.shopDao.countShopDistance(query);
        }
        List<ShopDistanceView> views = null;
        if (0 < total.intValue() || 0 >= query.getLimit().intValue()) {
            views = this.shopDao.pageShopDistance(query);
        }
        if (0 >= query.getLimit().intValue()) {
            if (null == views) {
                total = Integer.valueOf(0);
            } else {
                total = Integer.valueOf(views.size());
            }
        }
        return new PageResult(total, views);
    }*/


